import axios from 'axios'

export default {
  namespaced: true,
  state() {
    return {
      list: []
    }
  },
  mutations: {
    updateList(state, val) {
      state.list = val
    },
    // 修改数量
    updateCount(state, obj) {
      const row = state.list.find(item => item.id == obj.id)
      if (obj.value === -1 && row.goods_count === 1) return
      row.goods_count += obj.value
    },
    // 修改状态
    updateState(state, id) {
      const row = state.list.find(item => item.id == id)
      row.goods_state = !row.goods_state
    },
    setAllState(state, boo) {
      // console.log(boo)
      state.list.forEach(item => {
        item.goods_state = boo
      })
    }
  },
  actions: {
    async initData(store) {
      const {
        data: res
      } = await axios.get('http://www.itcbc.com:3006/api/cart')
      console.log(res);
      store.commit('updateList', res.list)
    }
  },
  getters: {
    // 计算已选商品总数量
    total(state) {
      // 先找出所有选中的商品
      const a = state.list.filter(item => item.goods_state)
      // console.log(a)
      // 计算上述商品的总数量
      return a.reduce((t, c) => t + c.goods_count, 0)
    },
    // 计算已选商品总价格
    amount(state) {
      // 先找出所有选中的商品
      const a = state.list.filter(item => item.goods_state)
      return a.reduce((t, c) => t + c.goods_price * c.goods_count, 0)
    },
    // 计算是否选中了
    isFull(state) {
      return state.list.every(item => item.goods_state)
    }
  }
}
